import { useRequest } from "ahooks";
import { doFetch } from "./doFetch";
import { useModel } from '@umijs/max';

export default function useCurrentUser() {
    const {
        initialState,
        setInitialState,
    } = useModel('@@initialState');

    const { fetchUserInfo, currentUser } = initialState;


    const updateUser = useRequest(
        async (params) => {
            const res = await doFetch({
                url: `/system/user`,
                params,
                method: 'PUT',
            })
            if (res?.code === 0) {
                return fetchUserInfo();
            } else {
                return null;
            }
        },
        {
            manual: true,
            onSuccess: (res) => {
                if (!res) return;
                setInitialState((s) => ({
                    ...s,
                    currentUser: res,
                }));
            },
        },
    );

    const getUser = useRequest(
        async () => {
            return fetchUserInfo();
        },
        {
            manual: true,
            onSuccess: (res) => {
                if (!res) return;
                localStorage.setItem('ID', res?.id);
                setInitialState((s) => ({
                    ...s,
                    currentUser: res,
                }));
            },
        },
    );

    return { initialState,setInitialState, updateUser, currentUser, getUser };
}